﻿using Protocol.SouthGridProtocol.Blocks;
using Protocol.SouthGridProtocol.Decoder;
using Protocol.SouthGridProtocol.Encoder;
using PacoToolKit.Format;
using System.Collections.Generic;
using System.Text;
namespace Protocol.SouthGridProtocol.Model
{
    public class C04H
    {
        private static string head = "68";
        private static string bottom = "16";
        private static string tp = BaseEncoder.CreateTP();

        private static string afn = "04";

        private static Seq seq = new Seq(1, 1, 1, 1, 1);//con=1,
        private static C c = new C(0, 1, 1, null, 0, 10);//prm=1,funcode=10

        /// <summary>
        /// 
        /// </summary>
        /// <param name="concentrator"></param>
        /// <param name="dataList"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static string EncodeC04H(string concentrator, List<CData> dataList, string password)
        {
            //主站启动的发送帧的MSA应为非零值,终端启动发送帧的MSA应为零，其主站响应帧的MSA也应为零
            concentrator = concentrator.Substring(0, 12) + "01";
            StringBuilder sb = new StringBuilder();
            foreach (CData data in dataList)
            {
                sb.Append(data.da); sb.Append(data.di); sb.Append(data.data);
            }
            string length = BaseEncoder.CalcLength(c.encodeC() + concentrator + afn + seq.encodeSeqString() + sb.ToString() + password + tp);
            string cs = BaseEncoder.CalcCSCode(c.encodeC() + concentrator + afn + seq.encodeSeqString() + sb.ToString() + password + tp);
            return head + length + length + head + c.encodeC() + concentrator + afn + seq.encodeSeqString() + sb.ToString() + password + tp + cs + bottom;
        }
        /// <summary>
        /// 解析下发集中器参数返回的成功失败信息
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static List<CData> DecodeC04H(string msg)
        {
            List<CData> dataList = new List<CData>();

            int msgLength = BaseDecoder.GetLength(msg);//字节数


            int dataRemainLen = (msgLength - 10) * 2;//初始 剩余未读数据长度
            string dataRemain = msg.Substring(32, dataRemainLen);//初始 剩余未读数据

            //循环读取块
            while (dataRemainLen >= 12)
            {
                string da = dataRemain.Substring(0, 4);
                string di = dataRemain.Substring(4, 8);
                int currentDataBlockLength = 1;
                string data = dataRemain.Substring(12, currentDataBlockLength * 2);

                dataList.Add(new CData { da = da, di = di, data = data });//读完一块，加入列表

                //重新计算剩余未读数据
                dataRemain = dataRemain.Remove(0, (4 + 8 + currentDataBlockLength * 2));
                dataRemainLen = dataRemain.Length;
            }

            return dataList;
        }
    }
}
